/*
 * @Author: silence
 * @Date: 2023-06-30 14:51:45
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-01-04 10:48:58
 * @Description: 首页-设备基础信息（是否在线、电量、功率）
 */
import 'package:ems_neutral_app/bloc/userbloc/user_bloc.dart';
import 'package:ems_neutral_app/entities/DeviceEntity.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';

import '../../../common/widgets/cubitWidget/BottomSheetView.dart';
import '../../../utils/eventBus/eventBus.dart';
import '../../../utils/string/StringConstant.dart';
import '../../PowerStation/Controller/PowerStationController.dart';
import '../../PowerStation/Detail/PowerStationDetailPage.dart';
import 'HomePowerProgressView.dart';

class HomeDeviceBaseInfoView extends StatefulWidget {
  const HomeDeviceBaseInfoView({super.key});

  @override
  State<HomeDeviceBaseInfoView> createState() => _HomeDeviceBaseInfoViewState();
}

class _HomeDeviceBaseInfoViewState extends State<HomeDeviceBaseInfoView> {
  PowerStationController _powerStationController =
      Get.put(PowerStationController());

  @override
  Widget build(BuildContext context) {
    return Obx(() => mainView());
  }

  mainView() {
    String? stationType =
        _powerStationController.powerStationEntity.value.stationType;
    return Container(
      padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top + 30,
          bottom: 40.w,
          left: 20.w,
          right: 20.w),
      decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage(stationType == '3'
                  ? 'imgs/home/home_bg_e3.png'
                  : 'imgs/home/home_bg.png'),
              fit: BoxFit.fitWidth,
              alignment: Alignment.topCenter)),
      child: Column(
        children: [
          /// logo
          SilImage('imgs/login/logo@3x.png',
              height: 14.w,
              margin: EdgeInsets.only(top: 10.w, bottom: 20.w),
              alignment: Alignment.centerLeft),

          /// 电站状态
          Obx(() => powerStateView()),

          /// 实时电量、功率（进度）
          HomePowerProgressView(),

          /// 详细收益
          detailedBenefitsView(),
        ],
      ),
    );
  }

  /// 电站状态
  powerStateView() {
    List list = _powerStationController.myPowerStationNameList;

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Obx(() => SilText(
                _powerStationController.powerStationEntity.value.ps_name,
                color: ColorUtils.color_font_main,
                fontSize: 16.sp,
              )),
          if (!SilTools.listIsEmpty(list))
            SilButton(
              imgPath: 'imgs/home/home_change_power.png',
              imgHeight: 25.w,
              imgWidth: 25.w,
              onTapFunc: showMyPowerStationListPopView,
            )
        ],
      ),
    );
  }

  /// 显示我的电站列表
  showMyPowerStationListPopView() {
    List<String> titleList = [];

    List list = _powerStationController.myPowerStationNameList;
    List deviceList = _powerStationController.myPowerStationList;

    // 当前选中的电站id
    String curPowerStation = UserBlocTool.userEntity?.powerRecordId ?? "";
    int initialSelectedItem = 0;

    for (var i = 0; i < deviceList.length; i++) {
      DeviceEntity entity = deviceList[i];
      if (curPowerStation == entity.id) {
        initialSelectedItem = i;
      }
      titleList.add(list[i]);
    }

    SilBottomSheet.show(
        context: context,
        child: BottomSheetView(
          initialSelectedItem: initialSelectedItem,
          titles: titleList,
          tapSureSeletedFunc: (selected) {
            DeviceEntity entity = deviceList[selected];

            _powerStationController.changePowerStation(context,
                powerRecordId: entity.id);
          },
        ));
  }

  /// 详细收益
  detailedBenefitsView() {
    return Container(
      margin: EdgeInsets.only(top: 150.w),
      child: Column(
        children: [
          /// 标题
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SilButton(
                imgPath: 'imgs/home/home_money.png',
                imgHeight: 25.w,
                imgWidth: 25.w,
                title: LangOf(context)?.index?.detail_balance,
                titleColor: ColorUtils.color_font_main,
                fontSize: 16.sp,
                imagePosition: ImagePosition.Left,
              ),
              SilButton(
                imgPath: 'imgs/home/home_back_blue.png',
                imgHeight: 25.w,
                imgWidth: 25.w,
                padding: EdgeInsets.only(left: 15.w),
                onTapFunc: () {
                  ARoute.gotoPage(
                      context,
                      PowerStationDetailPage(
                        powerStationEntity:
                            _powerStationController.powerStationEntity.value,
                      ));
                },
              ),
            ],
          ),

          /// 具体电量信息（发电量、买电量、卖电量、用电量）
          Obx(() => specificEnergyInfoView()),

          /// 具体收益
          Obx(() => specificIncomeView()),
        ],
      ),
    );
  }

  /// 具体电量信息（发电量、买电量、卖电量、用电量）
  specificEnergyInfoView() {
    List<String?> itemTitles = [];
    itemTitles.add(LangOf(context)?.index?.generated);
    itemTitles.add(LangOf(context)?.index?.purchased);
    itemTitles.add(LangOf(context)?.index?.sold);
    itemTitles.add(LangOf(context)?.index?.gc);

    List<String?> itemValues = ['0', '0', '0', '0'];
    itemValues[0] = _powerStationController
        .powerStationEntity.value.oneGenerationStr; // 发电量
    itemValues[1] = _powerStationController
        .powerStationEntity.value.onePayElectricStr; // 买电量
    itemValues[2] = _powerStationController
        .powerStationEntity.value.oneSellElectricStr; // 卖电量
    itemValues[3] = _powerStationController
        .powerStationEntity.value.electricityConsumptionStr; // 用电量

    List<Widget> itemWidgets = [];
    for (var i = 0; i < itemTitles.length; i++) {
      SilText titleWidget = SilText(
        itemTitles[i],
        color: ColorUtils.color_font_main,
        fontSize: 13.sp,
        maxLines: 0,
        textAlign: TextAlign.center,
      );
      SilText valueWidget = SilText("${itemValues[i]}kWh",
          color: ColorUtils.color_font_main,
          fontSize: 13.sp,
          maxLines: 0,
          textAlign: TextAlign.center);
      itemWidgets.add(Expanded(
          child: SilTextIconButton(
        titleWidget,
        valueWidget,
        space: 6.w,
        imagePosition: ImagePosition.Down,
      )));
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      margin: EdgeInsets.only(top: 25.w),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: itemWidgets),
    );
  }

  /// 具体收益
  specificIncomeView() {
    List<String?> itemTitles = [];
    itemTitles.add(LangOf(context)?.index?.generated_income); // 发电收益
    itemTitles.add(LangOf(context)?.index?.purchased_cost); // 买电费用
    itemTitles.add(LangOf(context)?.index?.sold_income); // 卖电收益
    itemTitles.add(LangOf(context)?.index?.gcprice); // 用电费用

    List<String?> itemValues = ['0', '0', '0', '0'];
    itemValues[0] = _powerStationController
        .powerStationEntity.value.oneGaRevenueStr; // 发电收益
    itemValues[1] = _powerStationController
        .powerStationEntity.value.onePayElectricMoneyStr; // 买电费用
    itemValues[2] = _powerStationController
        .powerStationEntity.value.oneSellElectricMoneyStr; // 卖电收益
    itemValues[3] = _powerStationController
        .powerStationEntity.value.electricityCostStr; // 用电费用
    List<Widget> itemWidgets = [];

    /// 价格单位
    String moneyUnit =
        _powerStationController.powerStationEntity.value.moneyUnit ?? "";

    double powerPrice = double.parse(
        _powerStationController.powerStationEntity.value.powerPrice ?? '0.0');
    bool emptyPowerPrice = powerPrice == 0;
    for (var i = 0; i < itemTitles.length; i++) {
      SilText titleWidget = SilText(itemTitles[i],
          color: ColorUtils.color_font_main,
          fontSize: 13.sp,
          maxLines: 0,
          textAlign: TextAlign.center);

      /// 收益，判断一下电价为0时，显示图片
      Widget valueWidget = SilText(
        "${moneyUnit}${itemValues[i]}",
        color: ColorUtils.color_font_main,
        fontSize: 13.sp,
        maxLines: 0,
        textAlign: TextAlign.center,
      );

      if (emptyPowerPrice) {
        valueWidget = SilButton(
          imgPath: 'imgs/home/home_notice.png',
          imgHeight: 16.w,
          imgWidth: 16.w,
          onTapFunc: () => bus.emit(StringConstant.APPGotoTabbar, 1),
        );
      }

      itemWidgets.add(Expanded(
          child: SilTextIconButton(
        titleWidget,
        valueWidget,
        space: 6.w,
        imagePosition: ImagePosition.Down,
      )));
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      margin: EdgeInsets.only(top: 25.w),
      child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: itemWidgets),
    );
  }
}
